import { Directive } from 'vue'

interface AnimateElement extends HTMLElement {
  observer?: IntersectionObserver
}

export const animateOnScroll: Directive = {
  mounted(el: AnimateElement, binding) {
    // 获取延迟参数
    const delay = binding.value || 0
    
    // 创建交叉观察器
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            // 延迟后添加动画类
            setTimeout(() => {
              el.classList.add('animate')
            }, delay * 100)
            
            // 元素进入视口后停止观察
            observer.unobserve(el)
          }
        })
      },
      { threshold: 0.15 }
    )
    
    // 保存观察器实例
    el.observer = observer
    
    // 开始观察元素
    observer.observe(el)
  },
  
  unmounted(el: AnimateElement) {
    // 组件卸载时停止观察
    el.observer?.disconnect()
  }
}
